package controller

import (
	"daocloud.io/dmp/demo/global"
	"daocloud.io/dmp/demo/model"
	"daocloud.io/dmp/demo/response"
	"daocloud.io/dmp/demo/service"
	"encoding/json"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

/**
 * @author  liyuan.zhang
 * @date  2021/2/24 17:32
 */

func FindUserById(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Param("userId"))
	log.Printf("The user ID you are looking for is %d", userId)
	user := model.User{}
	if err := service.FindUserById(userId, &user); err != nil {
		c.JSON(http.StatusInternalServerError, response.DataBaseFail(err))
		return
	}
	c.JSON(http.StatusOK, response.Response{
		Code:  http.StatusOK,
		Data:  user,
		Msg:   "查询成功",
		Error: "",
	})
}

func AddUser(c *gin.Context) {
	user := model.User{}
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	if err := service.AddUser(&user); err != nil {
		c.JSON(http.StatusInternalServerError, response.DataBaseFail(err))
		return
	}
	FindAllUser(c)
}

func FindAllUser(c *gin.Context) {
	users := make([]model.User, 0)
	if err := service.FindAllUsers(&users); err != nil {
		c.JSON(http.StatusInternalServerError, response.DataBaseFail(err))
		return
	}
	c.JSON(http.StatusOK, response.Response{
		Code:  http.StatusOK,
		Data:  users,
		Msg:   "查询成功",
		Error: "",
	})
}

func TestRedis(c *gin.Context) {
	user := model.User{
		Id:       1,
		UserName: "张三",
		Password: "123",
	}
	// json序列化
	datas, _ := json.Marshal(user)
	global.REDISDB.Do("set", "user", datas)
	// 读取数据
	bytes, _ := redis.Bytes(global.REDISDB.Do("get", "user"))
	fmt.Println(global.REDISDB.Do("get", "user"))
	// json反序列化
	u := model.User{}
	if err := json.Unmarshal(bytes, u); err != nil {
		fmt.Println("json反序列化失败")
	}
	c.JSON(200, u)
}
